package com.example.socket.codec;

import com.example.socket.core.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通信消息({@link Message})编码器
 * @author frank
 */
public class MessageEncoder extends MessageToByteEncoder<Message> {

    private static final Logger logger = LoggerFactory.getLogger(MessageEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) {
        CompositeByteBuf byteBuf = (CompositeByteBuf) out;
        ByteBufAllocator alloc = ctx.alloc();
        ByteBuf buffer = msg.toBuffer(byteBuf, alloc);
        if (logger.isDebugEnabled()) {
            logger.debug("编码:{}", buffer.toString());
        }
    }

    @Override
    protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, Message msg, boolean preferDirect) {
        if (isPreferDirect()) {
            return ctx.alloc().compositeDirectBuffer();
        } else {
            return ctx.alloc().compositeHeapBuffer();
        }
    }
}
